<template>
  <div class="container">
    <Card shadow>
      <div class="title mb-10">
        <Divider style="margin-top: 10px;">
          <h3 style="text-align: center;color: #17233d;">
            <span v-if="currStudyYear">{{ currStudyYear }} ~ {{ Number(currStudyYear) + 1}}学年</span>
            <span v-if="currSemester !== ''">第{{['一', '二'][currSemester]}}学期</span>
            <span>{{ this.filter.week ? '第' + this.filter.week + '周' : '周次' }}安排表</span>
          </h3>
        </Divider>
      </div>
      <div class="top-toolbar pr-10 pl-10">
        <Row type="flex" align="middle" class="position-relative">
          <Col :xs="24" :sm="24" :md="24" :lg="7" class="mb-15">
            <span>学院：</span>
            <div style="display: inline-block;width: calc(100% - 42px);">
              <Select v-if="userAccess.some(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN', 'ROLE_INSTITUTE_ADMIN', 'ROLE_TEACHER'].indexOf(item) > -1 })"
                      :size="selectSize"
                      v-model="filter.institute"
                      :enabledPreventOverflow="enabledPreventOverflow"
                      placeholder="请选择学院进行检索"
                      filterable
                      @on-change="onChangeInstitute">
                <Option v-for="(item, index) in institutes" :value="item" :key="index">{{ item }}</Option>
              </Select>
              <Input v-else v-model="filter.institute" readonly placeholder="当前学院" />
            </div>
          </Col>
          <Col :xs="24" :sm="24" :md="{span: 11}" :lg="{span: 6, offset: 1}" class="mb-15">
            <span>周次：</span>
            <Select style="width: calc(100% - 42px);"
                    :size="selectSize"
                    v-model="filter.week"
                    :enabledPreventOverflow="enabledPreventOverflow"
                    placeholder="请选择周次进行检索"
                    filterable
                    @on-change="onChangeWeek">
              <Option v-for="n in 20" :value="n" :key="n">第 {{ n }} 周</Option>
            </Select>
          </Col>
          <Col :xs="24" :sm="24" :md="{span: 11, offset: 2}" :lg="{span: 6, offset: 1}" class="mb-15">
            <span>星期：</span>
            <Select style="width: calc(100% - 42px);"
                    :size="selectSize"
                    v-model="filter.weekday"
                    :enabledPreventOverflow="enabledPreventOverflow"
                    placeholder="请选择星期几进行检索"
                    filterable
                    :disabled="!filter.week"
                    @on-change="onChangeWeekday">
              <Option value="all" key="all">全部</Option>
              <Option v-for="(item, index) in weekdays" :value="index + 1" :key="index">{{ item }}</Option>
            </Select>
          </Col>
          <Col :xs="24" :sm="24" :md="4" :lg="2" class="btn-container mb-15" v-if="this.userAccess.some(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN', 'ROLE_INSTITUTE_ADMIN'].indexOf(item) > -1 })">
            <Button class="export-btn" :loading="exportLoading" @click="exportToExcel" :size="btnSize">
              <font-awesome-icon icon="file-excel" v-if="!exportLoading" />
              导出
            </Button>
          </Col>
        </Row>
      </div>
      <div class="weekly-schedule-container">
        <weekly-schedule ref="weeklySchedule" :filter="filter"></weekly-schedule>
      </div>
    </Card>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import WeeklySchedule from '_c/weekly-schedule'
import { getInstituteList, getCurrTermDateInfo } from '@/api/weekly-schedule'
import { on, off, trim } from '@/libs/tools'
import { s2ab } from '@/libs/excel'
import { library } from '@fortawesome/fontawesome-svg-core'
import { faFileExcel } from '@fortawesome/free-solid-svg-icons'
library.add(faFileExcel)

export default {
  name: 'weekly_schedule',
  components: {
    // 使用 key: value 的形式注册 value 组件，并命名为 key
    'weekly-schedule': WeeklySchedule
  },
  data () {
    return {
      firstEnter: false,
      btnSize: 'default',
      selectSize: 'default',
      enabledPreventOverflow: false,
      weekdays: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'],
      filter: {
        institute: '',
        week: '',
        weekday: 'all'
      },
      currStudyYear: '',
      currSemester: '',
      currWeek: '',
      userAccess: [],
      institutes: [],
      exportLoading: false
    }
  },
  methods: {
    ...mapActions([
      'getUserInfo'
    ]),
    onChangeInstitute (value) {
      this.filter.institute = value
    },
    onChangeWeek (value) {
      this.filter.week = value
      if (!this.filter.week) {
        this.$Notice.info({
          title: '提示',
          desc: '请先选择周次进行检索！'
        })
      }
    },
    onChangeWeekday (value) {
      this.filter.weekday = value
    },
    resizeSubComponents () {
      this.$children[0].$el.children[0].style.minHeight = this.$parent.$el.clientHeight - 36 + 'px'
      this.$refs.weeklySchedule.tableHeight = this.$el.clientHeight - 143
    },
    exportToExcel () {
      this.exportLoading = true
      const table = document.querySelector('#weekly-schedule .ivu-table')
      // 学年
      let title = this.currStudyYear ? this.currStudyYear + '~' + (Number(this.currStudyYear) + 1) + '学年' : ''
      // 学期
      title += this.currSemester !== '' ? '第' + ['一', '二'][this.currSemester] + '学期-' : ''
      // 学院
      title += this.filter.institute ? this.filter.institute + '-' : ''
      // 周次
      title += this.filter.week ? '第' + this.filter.week + '周-' : ''
      // 星期
      title += this.filter.weekday && this.filter.weekday !== 'all' ? this.weekdays[this.filter.weekday - 1] + '-' : ''
      title += '周次安排表'
      const fileName = title
      const wb = this.$xlsx.utils.book_new()
      const ws = this.$xlsx.utils.table_to_sheet(table, {
        raw: true,
        display: true,
        ignoreEC: true
      })
      // const border = {
      //   border: {
      //     top: {
      //       style: 'medium'
      //     },
      //     bottom: {
      //       style: 'medium'
      //     },
      //     left: {
      //       style: 'medium'
      //     },
      //     right: {
      //       style: 'medium'
      //     }
      //   }
      // }
      const center = {
        alignment: {
          vertical: 'center',
          wrapText: true,
          horizontal: 'center'
        }
      }
      // 遍历所有单元格进行样式的处理
      Object.keys(ws).forEach(k => {
        if (k !== '!merges' && k !== '!ref') {
          // 去掉内容前后所有的空格
          ws[k].v = trim(ws[k].v)
          // 把内容中间的所有**进行换行
          ws[k].v = ws[k].v.replace(/\*\*/g, '\n')
          // 添加center和border样式
          if (ws[k].v) {
            ws[k].s = {...center,
              ...{
                font: {
                  name: 'Microsoft YaHei'
                }
              }
            }
          }
          // 给特定单元格添加背景色
          if (ws[k].v && k.charAt(0) !== 'A' && k.charAt(0) !== 'B' && ((k.length === 2 && k.charAt(1) !== '1') || k.length !== 2)) {
            Object.assign(ws[k].s.font, {
              color: {
                rgb: 'FF276F86'
              },
              bold: true
            })
            Object.assign(ws[k].s, {
              fill: {
                fgColor: {
                  rgb: 'FFEBF7FF'
                }
              }
            })
          }
          if (ws[k].v === '暂无筛选结果') {
            delete ws[k]
          }
        }
      })
      this.$xlsx.utils.book_append_sheet(wb, ws, '周次安排表')
      const wbout = this.$xls.write(wb, { bookType: 'xlsx', type: 'binary' })
      this.$fileSaver.saveAs(new Blob([s2ab(wbout)], { type: '' }), fileName + '.xlsx')
      this.exportLoading = false
    }
  },
  created () {
    this.firstEnter = true
    this.$Notice.config({
      top: window.innerHeight / 3
    })
    // 获取当前的学年、学期、周次
    getCurrTermDateInfo().then(response => {
      let res = response.data
      if (res.code === 1) {
        this.currStudyYear = res.data.studyYear
        this.currSemester = res.data.semester
        this.filter.week = this.currWeek = res.data.week
      } else {
        this.$Notice.error({
          title: '获取数据失败',
          desc: '获取当前学年、学期和周次失败！' + res.info + '请重试！'
        })
      }
      if (!this.filter.week) {
        this.$Notice.info({
          title: '提示',
          desc: '请先选择周次进行检索！'
        })
      }
    }).catch(error => {
      console.log(error)
      this.$Notice.error({
        title: '获取数据失败',
        desc: '获取当前学年、学期和周次失败！请重试！'
      })
      if (!this.filter.week) {
        this.$Notice.info({
          title: '提示',
          desc: '请先选择周次进行检索！'
        })
      }
    })
    // 获取用户信息
    this.getUserInfo().then(response => {
      let res = response.data
      if (res.code === 1) {
        res = res.data
        this.userAccess = res.roles || []
        this.filter.institute = this.userAccess.indexOf('ROLE_STUDENT_ASSISTANT') > -1 ? (res.workDepartment || '') : (res.department || '')
        if (this.userAccess.some(item => { return ['ROLE_ROOT', 'ROLE_SCHOOL_ADMIN', 'ROLE_INSTITUTE_ADMIN', 'ROLE_TEACHER'].indexOf(item) > -1 })) {
          // 获取所有学院
          getInstituteList().then(response => {
            let res = response.data
            if (res.code === 1) {
              this.institutes = res.data.length > 0 ? res.data : []
            } else {
              this.$Notice.error({
                title: '获取列表失败',
                desc: '获取学院列表失败！' + res.info
              })
            }
          }).catch(err => {
            this.$Notice.error({
              title: '获取列表失败',
              desc: '获取学院列表失败！'
            })
            console.log(err)
          })
        }
      } else {
        this.$Notice.error({
          title: '获取信息失败',
          desc: '获取用户信息失败！' + res.info
        })
      }
    }).catch(err => {
      this.$Notice.error({
        title: '获取信息失败',
        desc: '获取用户信息失败！'
      })
      console.log(err)
    })
  },
  mounted () {
    this.$nextTick(() => {
      this.resizeSubComponents()
      on(window, 'resize', this.resizeSubComponents)
    })
  },
  activated () {
    if (!this.firstEnter) {
      this.resizeSubComponents()
      on(window, 'resize', this.resizeSubComponents)
      this.$Notice.config({
        top: window.innerHeight / 3
      })
      if (!this.filter.week) {
        this.$Notice.info({
          title: '提示',
          desc: '请先选择周次进行检索！'
        })
      }
    }
  },
  deactivated () {
    this.firstEnter = false
    off(window, 'resize', this.resizeSubComponents)
    this.$Notice.destroy()
  },
  beforeDestroy () {
    off(window, 'resize', this.resizeSubComponents)
    this.$Notice.destroy()
  }
}
</script>

<style lang="less" scoped>
  @import 'weekly-schedule.less';
</style>
